import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { Toggle } from '../../components/Toggle';
import { Button } from '../../components/Button';
import { Modal } from '../../components/Modal';
import './RemindersSection.css';

export const RemindersSection = () => {
  const [reminders, setReminders] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);

  useEffect(() => {
    loadReminders();
  }, []);

  const loadReminders = async () => {
    chrome.storage.local.get(['reminders'], (result) => {
      setReminders(result.reminders || []);
    });
  };

  return (
    <section className="reminders-section">
      <div className="section-header">
        <h2>Reminders</h2>
        <Button onClick={() => setShowAddModal(true)}>+ Add Reminder</Button>
      </div>

      <div className="reminders-grid">
        {reminders.map((reminder) => (
          <Card key={reminder.id} className="reminder-card">
            <div className="reminder-header">
              <h3>
                <span>{reminder.icon || '⏰'}</span>
                {reminder.title}
              </h3>
              <Toggle
                checked={reminder.enabled}
                onChange={(e) => handleToggle(reminder.id, e.target.checked)}
              />
            </div>
            {reminder.description && <p>{reminder.description}</p>}
          </Card>
        ))}
      </div>

      <Modal isOpen={showAddModal} onClose={() => setShowAddModal(false)} title="Add Custom Reminder">
        <form onSubmit={handleAddReminder}>
          <div className="form-group">
            <input type="text" name="title" placeholder="Title" required />
          </div>
          <div className="form-group">
            <textarea name="description" placeholder="Description" rows="2"></textarea>
          </div>
          <div className="form-group">
            <label>
              Frequency (minutes):
              <input type="number" name="frequency" min="1" defaultValue="60" required />
            </label>
          </div>
          <div className="form-group">
            <label>
              <input type="checkbox" name="enabled" defaultChecked /> Enable immediately
            </label>
          </div>
          <Button type="submit">Add Reminder</Button>
        </form>
      </Modal>
    </section>
  );

  async function handleToggle(reminderId, enabled) {
    const updatedReminders = reminders.map(r =>
      r.id === reminderId ? { ...r, enabled } : r
    );
    await chrome.storage.local.set({ reminders: updatedReminders });
    setReminders(updatedReminders);
  }

  async function handleAddReminder(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newReminder = {
      id: `custom-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: formData.get('title'),
      description: formData.get('description') || '',
      frequency: parseInt(formData.get('frequency')) || 60,
      enabled: formData.get('enabled') === 'on',
      custom: true,
      icon: '⏰',
      category: 'Custom',
      lastTriggered: null
    };

    const updatedReminders = [...reminders, newReminder];
    await chrome.storage.local.set({ reminders: updatedReminders });
    setReminders(updatedReminders);
    setShowAddModal(false);
    e.target.reset();
  }
};

